#encoding:utf8 

import os
import shutil
from subprocess import CalledProcessError
import time
from ccmd import Dlog
from lib.ucmd import run_and_check

class CocosPack:
    
    def __init__(self, env):
        self._env = env
    

    def pack(self, isclear=True): 
        '''
        打包cocos资源， 生成需更新文件及文件详细信息列表配置
        '''
        # 是否强制清理缓存
        if isclear:
            self.clear()
        self.__cocosbin_build()
        ret = self.__cocos_vergen()
        return ret

          
    def clear(self):
        '''
        清理cocos的打包过程临时文件
        '''
        p_lib = os.path.join(self._env.proj_path,"library")
        p_local = os.path.join(self._env.proj_path,"local")
        p_build = os.path.join(self._env.proj_path,"build")
        shutil.rmtree(p_lib, ignore_errors=True)
        shutil.rmtree(p_local, ignore_errors=True)
        shutil.rmtree(p_build, ignore_errors=True)


    def __cocosbin_build(self):
        cmd_str = '''
{cocosbin} \
--path {proj_path} \
--force \
--build \
"platform={platform}; \
debug={isdebug}; \
md5Cache=false; \
buildPath=./build;" \
        '''\
        .format(cocosbin = self._env.cocos_bin, proj_path=self._env.proj_path, platform=self._env.platform, isdebug="true" if self._env.is_debug else "false")
        Dlog.logger().info("[cocospack] run cmd:%s ", cmd_str)

        try:
            run_and_check(cmd_str)
        except CalledProcessError:
            Dlog.logger().error("[cocospack] failed cocosbin build")   

        
    def __cocos_vergen(self):
        # check node
        cmd_check_str = "node -v"
        try:
            run_and_check(cmd_check_str)
        except CalledProcessError:
            Dlog.logger().error("[cocspack]not found *node*,install it first!")

        # gen action
        nabuild_p = os.path.join(self._env.proj_path, "build/jsb-link/")
        cmd_str = '''{nodebin} \
        {help_js} \
        -v {ver_str}  \
        -u {remote_url} \
        -s {nabuild_p} \
        -d {tar_p} \
        ''' \
        .format(nodebin = "node", 
                help_js = os.path.join(self._env.proj_path, "version_generator.js"),
                ver_str = time.strftime("%Y%m%d%H%M%S", time.localtime()), 
                nabuild_p = nabuild_p,
                remote_url = self._env.hotpub_remote_url,
                tar_p = os.path.join(os.getcwd(), self._env.hotpub_dir))
        Dlog.logger().info("[cocospack] run cmd : %s", cmd_str)
        try:
            run_and_check(cmd_str)
        except CalledProcessError:
            Dlog.logger().error("[cocospack] gen act failed")
        return nabuild_p